(function($){
	$.ns("mediav");
	mediav.Grid = function(box, options) {
		var Cls = this,
			tpl = '<tr {#style}>',
			opts = this.options = $.extend({
				//"cm" : [{title: '日期', name : 'date', width : 100, sortable : true, align: 'left'}],
				"showCheckbox": true,
				"showStar": false,
				"fixedTitle": true
			}, options),
			table_html, cols_attr = [], html = [],
			container = this.container = $("#" + box);

		this.pageHandler = opts.handlePage;
		if (0 == container.length) return;
		container.css("position", "relative");

		table_html = '<div class="mvgrid"><table style="width:100%;table-layout:fixed;" border="0" cellpadding="0" cellspacing="0" class="grid">';
		html.push('<thead><tr>');
		
		if (opts.showStar) {
			html.push('<th style="text-align:center;">&nbsp;</th>');
			tpl += '<td style="text-align:center;"><span class="whiteIcon noborder{#star}" rid="{#ID}"></span></td>';
			cols_attr.push('<col width="25px">');
		}

		if (opts.showCheckbox) {
			html.push('<th style="text-align:center;padding:0;"><input type="checkbox" name="chkAll" /></th>');
			tpl += '<td style="text-align:center;padding:0;"><input type="checkbox" name="chkItem" id="chkItem_{#ID}" value="{#ID}" /></td>';
			cols_attr.push('<col width="30px">');
		}

		$.each(opts.cm, function(i, v) {
			var sort_class = "", w;

			if (v.sortable) {
				sort_class='class="sort" ';
			}

			tpl += '<td style="text-align:' + v.align + ';">{#' + v.name + '}</td>';

			html.push('<th ' + sort_class + 'style="text-align:' + (v.talign || "center") + ';white-space:nowrap;">' + v.title + '</th>');

			w = v.width;
			if (!w) {
				w = "100px";
			} else if (-1 == w.toString().indexOf("%")) {
				w = w + "px";
			}

			cols_attr.push('<col width="' + w + '">');
		});
		tpl += "</tr>";
		this.tpl = tpl;
		html.push('</tr></thead><tbody></tbody></table>');

		if (this.pageHandler) {
			html.push('<div class="page-s">共有<span id="total"></span>行，每页显示<select id="pageSize"><option value="5">5</option><option value="10">10</option><option value="25">25</option><option value="50">50</option></select> <span id="pagination"></span></div>');
		}

		html.push('</div>');

		container.html(table_html + cols_attr.join("") + html.join(""));

		container.delegate("table.grid tr", "mouseover", function() {
			$(this).addClass("hover");
		})
		.delegate("table.grid tr", "mouseout", function() {
			$(this).removeClass("hover");
		})
		.delegate("#pagination a", "click", function() {
			Cls.pageHandler(parseInt($(this).attr('p'), 10), $("#pageSize").val());
		})
		.delegate(".mvgrid .grid th.sort", "click", function() {
			var $this = $(this), thIndex = $this.index(), cmIndex = thIndex, page;

			if (opts.showCheckbox) {
				cmIndex = thIndex - 1;
			}
			if (opts.showStar) {
				cmIndex = thIndex - 1;
			}

			if (opts.cm[cmIndex].sortable) {
				if($this.hasClass("desc")) {
					$this.removeClass("desc").addClass("asc");
				} else if($this.hasClass("asc")){
					$this.removeClass("asc").addClass("desc");
				} else {
					$this.addClass("asc").siblings(".sort").removeClass("asc desc");
				}

				if(Cls.pageHandler) {
					$this.attr("title", cmIndex).siblings().attr("title", "");
					page = parseInt($this.parent(".mvgrid").find(".page-s .current").attr("p"), 10);
					Cls.pageHandler(page, $("#pageSize").val());
				} else {
					var rows = $(".mvgrid table.grid tbody tr"), asc = $this.hasClass("asc");

					rows.sort(function(a, b) {
						a = $(a).children("td").eq(thIndex).text();
						b = $(b).children("td").eq(thIndex).text();

						if(opts.cm[cmIndex].sorttype == "number") {
							var i = parseFloat(b[0].replace(/(\$|\,)/g, '')), n = parseFloat(a[0].replace(/(\$|\,)/g, ''));
							return asc ? n - i : i - n;
						} else {
							return asc ? a.localeCompare(b) : b.localeCompare(a);
						}
					});
					
					$(".mvgrid table.grid tbody").empty().append(rows);
					$(".mvgrid table.grid tbody tr:odd").addClass("odd");
					$(".mvgrid table.grid tbody tr.odd:even").removeClass("odd");
				}
			}
		})
		.delegate(":checkbox[name=chkItem]", "click", function() {
			var checked = this.checked, allChecked = !$(":checkbox[name=chkItem]", container).not(":checked").length;

			$(this).parents("tr").toggleClass("select", checked);
			$(":checkbox[name=chkAll]", container).attr("checked", allChecked);
		})
		.delegate("span.whiteIcon", "click", function() {
			var t = $(this), star;
			if (t.hasClass("redIcon")) {
				t.removeClass("redIcon");
				star = false;
			} else {
				t.addClass("redIcon");
				star = true;
			}
			if ("function" == typeof Cls.options.handleStar) {
				Cls.options.handleStar.call(this, t.attr("rid"), star);
			}
		})
		.delegate(":checkbox[name=chkAll]", "click", function() {
			var checked = this.checked;
			$(":checkbox[name=chkItem]", container).attr("checked", checked);
			$("tbody tr", container).toggleClass("select", checked);
		});

		$("#pageSize").bind("change", function() {
			Cls.options.handleSize(this.value);
		});

		if (opts.fixedTitle) {
			var el = $("table.grid", container).clone(true).prependTo(container).wrap("<div></div>").parent().hide();
			el.find(".grid").children('tbody').remove();
			$(window).resize(function(){
				el.width($(".mvgrid").width());
			})

			this.fixed_header = {
				element: el,
				height: el.height(),
				y: 0
			};

			$(window).scroll(function() {
				var e = Cls.fixed_header, el = e.element,
					p = el.parent(), st, pt, ph;

				if (p.is(':visible')) {
					st = parseInt($(window).scrollTop());
					pt = parseInt(p.offset().top);
					ph = parseInt(p.height());

					if (pt - st <= 0 && st + e.height < pt + ph) {
						el.width($(".mvgrid").width());
						var bro = $.browser;
						if(bro.msie) {
							if (bro.version == 6.0) {
								el.show().css({position: 'absolute', top: st - pt - 3});
							} else if (bro.version == 7.0) {
								el.show().css({position: 'fixed', top: 0, left: p.offset().left});
							} else {
								el.show().css({position: 'fixed', top: 0});
							}
						} else {
							el.show().css({position: 'fixed', top: 0});
						}
					} else {
						el.hide();
					}
				}
			});
		}
	};

	mediav.Grid.prototype = {
		setData : function(data) {
			var tpl = this.tpl,
				html = [];
			$.each(data.result, function(i, v) {
				v.style = (i % 2 != 0) ? 'class="odd"' : '';
				v.star = ("1" == v.star) ? ' redIcon' : '';
				
				for (var v2 in v) {
					if ("star" == v2) {
						continue;
					}

					if ((v[v2] == null || 0 == $.trim(v[v2].toString()).length) && v2 != 'style') {
						v[v2] = "--";
					} else if (typeof(v[v2]) == 'object') {
						var content = '';
						if (v[v2].text) {
							content = v[v2].text;
						} else if (v[v2].img) {
							content = '<img src="'+ v[v2].img + '">';
						} else {
							content = '--';
						}
						if (v[v2].href) {
							var target = v[v2].target ? ' target="' + v[v2].target + '"' : '';
							var className = v[v2].className ? ' class="' + v[v2].className + '"' : '';
							v[v2] = '<a href="' + v[v2].href + '"' + target + ' ' + className + '>' + content + '</a>';
						} else {
							v[v2] = content;
						}
					}
				}
				html.push(tpl.supplant(v));
			});

			$("table.grid tbody", this.container).html(html.join(""));
			$(":checkbox[name=chkAll]", this.container).attr("checked", false);

			if (this.pageHandler) {
				this.pagination(data.paginal);
			}
		},

		getSelected : function(){
			var ids = $(":checkbox[name=chkItem]", this.container).fieldValue();
			return ids;
		},

		pagination : function(paginal) {
			var page = parseInt(paginal.current),
				size = parseInt(paginal.size),
				total = parseInt(paginal.total),
				pages = Math.ceil(total / size),
				pageHtml = '';

			$('#total').html(total);
			$("#pageSize").val(size);

			if (page - 1 > 0) {
				pageHtml += '<a class="prev" href="javascript:void(0);" p="' + (page-1) + '">上一页</a>';
			} else {
				pageHtml += '<span class="prev disabled">上一页</span>';
			}

			var cp = page - 1,
				start = cp > 3 ? Math.max(Math.min(cp - 3, pages - 5), 0) : 0,
				end = cp > 3 ? Math.min(cp + 3, pages): Math.min(5, pages);

			if (start > 0) {
				var l = Math.min(2, start);
				for(var i = 0; i < l; i++) {
					appendItem(i);
				}
				if(2 < start) {
					pageHtml += '<span class="ps">...</span>';
				}
			}

			for(var i = start; i < end; i++) {
				appendItem(i);
			}

			if (end < pages) {
				if(pages - 2 > end) {
					pageHtml += '<span class="ps">...</span>';
				}
				var begin = Math.max(pages - 2, end);
				for(var i = begin; i < pages; i++) {
					appendItem(i);
				}
			}
			function appendItem(page_id) {
				page_id += 1;
				if (page_id == page) {
					pageHtml += '<span class="pc current" p="' + page_id + '">' + page_id + '</span>';
				} else {
					pageHtml += '<a href="javascript:void(0);" class="pc" p="' + page_id + '">' + page_id + '</a>';
				}
			}


			if (page + 1 <= pages) {
				pageHtml += '<a class="next" href="javascript:void(0);" p="' + (page + 1) + '">下一页</a>';
			} else {
				pageHtml += '<span class="next disabled">下一页</span>';
			}
			$('#pagination').html(pageHtml);
		}
	};


})(jQuery);